package admin.controller;

import admin.bean.Message;
import mvc.ResponseBody;
import admin.service.AdminService;
import admin.service.impl.AdminServiceImpl;
import util.JsonUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

public class AdminController {
    @ResponseBody("/AdminExpress/login.do")
    public String login(HttpServletRequest req, HttpServletResponse resp){
        //接收/AdminExpress/login.html传递过来的用户名和密码
        String userName = req.getParameter("userName");
        String passWord = req.getParameter("passWord");


        //调用service传递参数，并获取结果
        AdminService service = new AdminServiceImpl();
        boolean result = service.login(userName,passWord);

        //根据结果，返回不同的数据
        Message msg = null;
        if (result){
            msg = new Message(0,"登录成功");
            //同步更新登录时间和登录ip
            Date date = new Date();
            //获取用户登录的ip
            String ip = req.getRemoteAddr();
            service.updateLoginTimeAndIP(userName,date,ip);
            //保存登录页面用户的session值
            req.getSession().setAttribute("userName",userName);
        }else {
            msg = new Message(-1,"登录失败");
        }

        //将数据转换为JSON格式
        String Json = JsonUtil.toJSON(msg);

        //将JSON数据回复给ajax
        return Json;
    }

    @ResponseBody("/AdminExpress/logout.do")
    public String logout(HttpServletRequest req, HttpServletResponse resp){
        //1.    销毁session
        req.getSession().invalidate();
        //2.    给客户端回复消息
        Message msg = new Message(0,"退出登录");

        return JsonUtil.toJSON(msg);
    }


}
